package com.jeff.practice;

public class TicTacToeValidator {
    public static boolean isValidTicTacToe(String[] board) {
        // 计数 X 和 O 的数量
        int countX = 0;
        int countO = 0;

        for (String row : board) {
            countX += row.chars().filter(ch -> ch == 'X').count();
            countO += row.chars().filter(ch -> ch == 'O').count();
        }

        // 检查棋子数量的有效性
        if (countX < countO || countX > countO + 1) {
            return false;
        }

        // 检查胜利条件
        boolean xWins = checkWinner(board, 'X');
        boolean oWins = checkWinner(board, 'O');

        // 检查胜利条件的有效性
        if (xWins && oWins) {
            return false; // 同时有两个玩家获胜
        }

        if (xWins && countX != countO + 1) {
            return false; // X 胜利时，数量不符合
        }

        if (oWins && countX != countO) {
            return false; // O 胜利时，数量不符合
        }

        return true; // 有效状态
    }

    // 检查玩家是否胜利
    private static boolean checkWinner(String[] board, char player) {
        // 检查行
        for (int i = 0; i < 3; i++) {
            if (board[i].charAt(0) == player && board[i].charAt(1) == player && board[i].charAt(2) == player) {
                return true;
            }
        }

        // 检查列
        for (int j = 0; j < 3; j++) {
            if (board[0].charAt(j) == player && board[1].charAt(j) == player && board[2].charAt(j) == player) {
                return true;
            }
        }

        // 检查对角线
        if (board[0].charAt(0) == player && board[1].charAt(1) == player && board[2].charAt(2) == player) {
            return true;
        }
        if (board[0].charAt(2) == player && board[1].charAt(1) == player && board[2].charAt(0) == player) {
            return true;
        }

        return false; // 没有胜利
    }

    public static void main(String[] args) {
        String[] board1 = {"XOX", "O O", "XOX"};
        System.out.println(isValidTicTacToe(board1)); // 输出: false

        String[] board2 = {"XOX", "O O", "OXO"};
        System.out.println(isValidTicTacToe(board2)); // 输出: true

        String[] board3 = {"XXX", "O O", "XOX"};
        System.out.println(isValidTicTacToe(board3)); // 输出: false

        String[] board4 = {"XOX", "XOX", "OOO"};
        System.out.println(isValidTicTacToe(board4)); // 输出: false
    }
}
